﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Breed;
using Provenance.Infra.Repositories.Breed;
using Provenance.Write.Api.Application.Command.Breed;

namespace Provenance.Write.Api.Application.CommandHandler.Breed
{
    public class UpBreedHealthCommandHandler : IRequestHandler<UpBreedHealthCommand, ApiResult>
    {
        private readonly IBreedHealthRepository _breedHealthRepository;
        private readonly ILogger<UpBreedingInfoCommandHandler> _logger;
        private IMapper _mapper;
        public UpBreedHealthCommandHandler(IBreedHealthRepository breedHealthRepository, IMapper mapper, ILogger<UpBreedingInfoCommandHandler> logger)
        {
            _breedHealthRepository = breedHealthRepository;
            _mapper = mapper;
            _logger = logger;
        }
        public async Task<ApiResult> Handle(UpBreedHealthCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _breedHealthRepository.GetAsync(x => x.BreedHealthId == request.BreedHealthId);
                obj = _mapper.Map(request, obj);
                await _breedHealthRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error updating breed health: " + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
